<template>
	<!-- #ifdef APP -->
	<scroll-view style="flex:1">
	<!-- #endif -->
		<view class="top-title">
			基本信息：
		</view>
		<view class="row">
			<view class="row-name">
				单据编号
			</view>
			<view class="row-value">
				{{dataInfo.F_DJBH}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				会议议题
			</view>
			<view class="row-value">
				{{dataInfo.F_HYYT}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				开始时间
			</view>
			<view class="row-value">
				{{dataInfo.F_KSSJ}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				结束时间
			</view>
			<view class="row-value">
				{{dataInfo.F_JZSJ}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				会议类型
			</view>
			<view class="row-value">
				{{dataInfo.F_HYLX}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				申请单位
			</view>
			<view class="row-value">
				{{dataInfo.F_SQRDW}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				申 请 人
			</view>
			<view class="row-value">
				{{dataInfo.F_SQR}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				主  持  人
			</view>
			<view class="row-value">
				{{dataInfo.F_ZCR}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				主  会  场
			</view>
			<view class="row-value">
				{{dataInfo.F_ZHC}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				分  会  场
			</view>
			<view class="row-value">
				{{dataInfo.F_FHC}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				局、分公司领导
			</view>
			<view class="row-value">
				{{dataInfo.F_FGSLD}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				首席专家、副总师
			</view>
			<view class="row-value">
				{{dataInfo.F_FZS}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				参会人员
			</view>
			<view class="row-value">
				{{dataInfo.F_CHRY}}
			</view>
		</view>
		<view class="row">
			<view class="row-name">
				参会人数
			</view>
			<view class="row-value">
				{{dataInfo.F_CHRS}}
			</view>
		</view>
		<view class="down-btn">
			<view class="btn1" @click="downLoadAll">批量下载</view>
			<!-- <view class="btn1" @click="removeDownloadList">批量删除</view> -->
		</view>
		<table class="table" border center>
			<thead>
				<tr>
					<th scope="col">文件名称</th>
					<!-- <th scope="col" style="white-space: nowrap;">文件大小</th> -->
					<th scope="col">状态</th>
					<th scope="col">操作</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="(item,index) in dataInfo.MX_VALUE" :key="index">
					<td scope="row" class="df-coolor" @click="downLoad(item.columns,'open')">{{item.columns.F_FJMC}}
					</td>
					<!-- <td @click="downLoad(item.columns,'open')">{{item.columns.size}}</td> -->
					<td :style="item.columns.locaPath?'color: #ccc;':''">
						<a v-if="item.columns.locaPath" class="df-coolor"
							style="white-space: nowrap;color: #ccc;">已下载</a>
						<text v-else style="white-space: nowrap;">未下载</text>
					</td>
					<td style="white-space: nowrap;" @click="downLoad(item.columns,'open-down')">下载</td>
				</tr>
			</tbody>
		</table>
		<fui-toast ref="toast" v-if="oneDownOver">
			<view class="fui-toast__custom">
				<text class="fui-toast__txt"
					style="color:#fff;display: flex;flex-direction: column;justify-content: center;align-items: center;">正在下载...<text>速度{{downloadProgress}}MB/s</text></text>
			</view>
		</fui-toast>
		<fui-toast ref="toast2" v-if="allFileNum != nowFlieNum">
			<view class="fui-toast__custom">
				<text class="fui-toast__txt"
					style="color:#fff;display: flex;flex-direction: column;justify-content: center;align-items: center;">正在下载...
					<view style="display: flex;gap: 30px;">
						<text>第{{nowFlieNum}}/{{allFileNum}}文件</text><text>速度{{downloadProgress}}MB/s</text>
					</view>
				</text>
			</view>
		</fui-toast>
	<!-- #ifdef APP -->
	</scroll-view>
	<!-- #endif -->
</template>

<script setup>
	import {
		ref,
		watch
	} from "vue"
	import RequestURL from "../../util/request.js";
	import fuiToast from "@/components/fui-toast/fui-toast.vue"
	import {
		onLoad,
		onBackPress
	} from "@dcloudio/uni-app"
	let dataInfo = ref({})

	let toast = ref(null)
	let toast2 = ref(null)

	let bId = "";
	let downloadOverList = [];
	let allFileNum = ref(-1);
	let nowFlieNum = ref(0);
	let isBackButton = false;


	let getDataInfo = () => {
		var filesURL = RequestURL.getRequestURL('getMeetDBDetail');
		var businessId = bId;
		var userInfo = uni.getStorageSync('$state') || "{}";
		var userJSON = userInfo;
		var userid = userJSON.account;
		var version = userJSON.version;
		var tocket = userJSON.tocket;
		uni.request({
			url: filesURL,
			method: 'GET',
			timeout: 5000,
			dataType: 'json',
			data: {
				userid: userid,
				version: version,
				tocket: tocket,
				businessId: businessId
			},
			header: {
				'Accept': '*/*',
				'X-Requested-With': 'XMLHttpRequest',
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				console.log(res, '000000000000000000)))');
				let data = res.data;
				if (data.return_code == "SUCCESS") {
					data.values.MX_VALUE = JSON.parse(data.values.MX_VALUE)
					if (data.values && data.values.MX_VALUE && data.values.MX_VALUE.length) {
						for (let i = 0; i < data.values.MX_VALUE.length; i++) {
							console.log(data.values.MX_VALUE[i]);
							let item = data.values.MX_VALUE[i].columns;
							console.log(downloadOverList, 'downloadOverList');
							for (let j = 0; j < downloadOverList.length; j++) {
								if (downloadOverList[j].filePath && downloadOverList[j].filePath.indexOf(
										item.F_FJMC) != -1) {
									data.values.MX_VALUE[i].columns.locaPath = downloadOverList[i]
										.filePath;
								}
							}
						}
					}
					dataInfo.value = data.values;
					// console.log(JSON.parse(data.values.MX_VALUE));
				} else {
					// return callback(res.return_msg);
					uni.showToast({
						title: res.return_msg,
						icon: 'none',
						duration: 2000
					})
				}
			},
			fail: (res) => {
				uni.showToast({
					title: '服务器异常链接失败',
					icon: 'none',
					duration: 2000
				})
			},
		})
	}

	let downloadProgress = ref(0);
	let toastDuration = ref(0);
	let oneDownOver = ref(true)
	/**
	 * v 要下载的信息
	 * type  是否是批量下载
	 */
	let downLoad = (v, type) => {
		uni.hideToast()
		if (v.locaPath && type == 'open') {
			console.log('7777777');
			uni.getSavedFileInfo({
				filePath: v.locaPath,
				success(res) {
					console.log('888888', res);
					if (res.size > 0) {
						if (type == 'open') {
							uni.navigateTo({
								url: '/pages/pdf/pdf?url=' + v.locaPath
							})
						} else {
							v.locaPath = "";
							downLoad(v, type)
						}
					} else {
						v.locaPath = "";
						downLoad(v, type)
					}
				}
			})
		} else {
			var f_fileName = encodeURI(v.F_PATH + "/" + v.F_GUID + "-" + v.F_ORDE + ".pdf");
			var remote_url = 'http://10.16.0.128:8083/xjOA/' + decodeURI(f_fileName);
			console.log(remote_url, '0000000');
			if (type == 'open' || type == 'open-down') {
				// uni.showLoading({
				// 	title: '下载中'
				// });
				toast.value.show({
					duration: 99999999
				})
				console.log(v.locaPath, '7777');
				if (v.locaPath) {
					uni.removeSavedFile({
						filePath: v.locaPath,
						success: function(res) {
							console.log(res);
						},
						fail: function(err) {
							console.log(err);
						}
					})
				}
			}
			let downloadTask = uni.downloadFile({
				url: remote_url,
				success(res) {
					console.log(res, '++++++');
					oneDownOver.value = false
					setTimeout(() => {
						oneDownOver.value = true
					}, 500)
					uni.getSavedFileInfo({
						filePath: res.tempFilePath,
						success(value) {
							console.log(value, '---???????');
							if (value.size <= 0) {
								uni.showToast({
									title: '文件有误，请重新上传！',
									icon: 'none',
									duration: 2000
								});
								nowFlieNum.value++
							} else {
								uni.saveFile({
									tempFilePath: res.tempFilePath,
									success: function(obj) {
										var savedFilePath = obj.savedFilePath;
										RenameFile(savedFilePath, v.F_FJMC, (path) => {
											v.hasDown = true;
											v.locaPath = path;
											uni.getSavedFileList({
												success(res) {
													downloadOverList = res
														.fileList;
												}
											})
											if (type == 'open') {
												uni.navigateTo({
													url: '/pages/pdf/pdf?url=' +
														path
												})
											} else {
												nowFlieNum.value++
											}
										})
									},
									fail(err) {
										uni.showToast({
											title: '下载失败',
											icon: 'none',
											duration: 2000
										})
									}
								});
							}
						}
					})

				},
				fail(err) {
					uni.hideLoading();
					console.log(err, '?????????????????????????????????????????????????????????');
					uni.showToast({
						title: '下载失败',
						icon: 'none',
						duration: 2000
					})
				}
			})

			let lastTime = Date.now();
			let lastBytesWritten = 0;
			// 监听下载进度
			downloadTask.onProgressUpdate((res) => {
				console.log(res, 'BBBBBBBBBBBBBB');
				const currentTime = Date.now();
				const currentBytesWritten = res.totalBytesWritten;
				const timeDiff = (currentTime - lastTime) / 1000; // 时间差（秒）
				const bytesDiff = currentBytesWritten - lastBytesWritten; // 字节数变化

				// 计算实时网速（字节/秒）
				const speed = bytesDiff / timeDiff;

				// 更新上一次下载进度的时间和已下载的字节数
				lastTime = currentTime;
				lastBytesWritten = currentBytesWritten;

				// 将实时网速转换为更易读的单位（如 MB/s）
				const speedInKB = speed / (1024 * 1024);
				downloadProgress.value = speedInKB.toFixed(2);

				// if (res.progress == 100) {
				//  oneDownOver.value = false
				// 	setTimeout(()=>{
				// oneDownOver.value = true
				// 	},500)
				// }
			});
		}
	}
	/**
	 * 修改文件名。
	 * @param {旧的文件路径} oldFilePath 
	 * @param {新的文件名} newFileName 
	 */
	function RenameFile(oldFilePath, newFileName, cb) {
		setTimeout(() => {
			plus.io.resolveLocalFileSystemURL(oldFilePath, entry => {
				console.log('<<<<<<<', oldFilePath);
				entry.getParent(_oldFile => {
					console.log('>>>>>>', _oldFile);
					entry.moveTo(_oldFile, '/' + newFileName, newFilePath => {
						console.log('newFilePath', newFilePath.fullPath)
						cb(newFilePath.fullPath)
					})
				})
			})
		}, 200)
	}

	/**
	 * 批量删除
	 */
	let removeDownloadList = () => {
		if (downloadOverList.length > 0) {
			uni.showLoading({
				title: '删除中'
			});
			if (downloadOverList.length == 0) {
				uni.showToast({
					title: '暂无可删除文件',
					icon: 'none',
					duration: 2000
				})
				return 
			}
			for (let i = 0; i < downloadOverList.length; i++) {
				uni.removeSavedFile({
					filePath: downloadOverList[i].filePath
				})
				if (i == downloadOverList.length - 1) {
					setTimeout(() => {
						uni.getSavedFileList({
							success(res) {
								downloadOverList = res.fileList;
								if (res.fileList.length == 0) {
									for (let i = 0; i < dataInfo.value.MX_VALUE.length; i++) {
										let item = dataInfo.value.MX_VALUE[i].columns.locaPath = "";
									}
									uni.showToast({
										title: '删除成功',
										icon: 'none',
										duration: 2000
									})
								}
							},
							complete() {
								uni.hideLoading()
							}
						})
					}, 300)
				}
			}
		} else {
			uni.showToast({
				title: '删除成功',
				icon: 'none',
				duration: 2000
			})
		}

		setTimeout(() => {
			uni.hideToast()
		}, 4000)
	}

	/**
	 * 批量下载
	 */
	let downLoadAll = () => {
		nowFlieNum.value = 0;
		isBackButton = true;
		toast2.value.show({
			duration: 99999999
		})
		for (let i = 0; i < downloadOverList.length; i++) {
			uni.removeSavedFile({
				filePath: downloadOverList[i].filePath
			})
		}
		let allListNum = dataInfo.value.MX_VALUE.length;
		allFileNum.value = allListNum;
		for (let i = 0; i < dataInfo.value.MX_VALUE.length; i++) {
			if (dataInfo.value.MX_VALUE[i] && dataInfo.value.MX_VALUE[i].columns) {
				downLoad(dataInfo.value.MX_VALUE[i].columns, 'down', {
					lastTime: Date.now(),
					lastBytesWritten: 0
				})
			}
		}
	}

	watch(() => nowFlieNum.value, (n, o) => {
		if (n == allFileNum.value) {
			isBackButton = false
			setTimeout(() => {
				nowFlieNum.value = 0
			}, 800)
		}
	})


	onLoad((query) => {
		bId = query.id;
		uni.getSavedFileList({
			success(res) {
				downloadOverList = res.fileList;
				getDataInfo()
			},
			complete(err) {
				console.log(err, '----=-=-=-');
			}

		})
	})
	onBackPress((options) => {
		// 点击虚拟键或者侧滑的时候触发（不允许返回）
		if (options.from === 'backbutton' || options.from === "navigateBack") {
			return isBackButton
		}
	})
</script>

<style lang="scss" scoped>
	* {
		font-size: 16px;
	}

	.top-title {
		padding: 10px;
		background: #eee;
		color: #aaa;
	}

	.row {
		display: flex;
		align-items: center;
		padding: 10px 15px;
		border-bottom: 1px solid #eee;

		.row-name {
			flex-shrink: 0;
			width: 100px;
		}
	}

	.down-btn {
		display: flex;
		align-items: center;
		gap: 20px;
		padding: 10px 20px;

		.btn1,
		a {
			color: #0fa0e9;
			text-decoration: underline;
		}
	}

	.table {
		width: 100%;
		letter-spacing: 1px;
		border-collapse: collapse;

		thead {
			width: 100%;
			background: #eee;
			box-sizing: border-box;
		}

		th,
		td {
			border: 1px solid #ccc;
			text-align: center;
			padding: 20px 10px;
			// white-space:nowrap; 
		}

		td {
			text-decoration: underline;
			cursor: pointer;
			color: #0fa0e9;

			a {
				color: #0fa0e9;
			}

			&.df-coolor {
				color: #000;
			}
		}
	}
</style>